<template>
  <div class="mx-auto h-full flex flex-col px-20">
    <div class="flex flex-1 items-center">
      <ProviderSelect :items="providers" v-model="currentProvider" />
    </div>
    <div class="flex items-center m-5">
      <MessageInput
        @create="createConversation"
        :disabled="currentProvider === ''"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import dayjs from "dayjs";
import ProviderSelect from "../components/ProviderSelect.vue";
import MessageInput from "../components/MessageInput.vue";

import { useProviderStore } from "../stores/provider";
const providerStore = useProviderStore();
const providers = computed(() => providerStore.items);

import { useConversationStore } from "../stores/conversation";
import { useRouter } from "vue-router";
const router = useRouter();
const conversationStore = useConversationStore();
// aliyun/qwen-turbo
//
const currentProvider = ref("aliyun/qwen-vl-plus");

const createConversation = async (question: string, imagePath?: string) => {
  const [AI_providerName, AI_modelName] = currentProvider.value.split("/");

  let copiedImagePath: string | undefined;
  if (imagePath) {
    try {
      copiedImagePath = await window.electronAPI.copyImageToUserDir(imagePath);
    } catch (error) {
      console.error("拷贝图片失败:", error);
    }
  }

  // 用 dayjs 得到格式化的当前时间字符串
  const currentTime = dayjs().format("YYYY-MM-DD HH:mm:ss");

  // pinia 中新建会话，得到新的会话id
  const conversationId = await conversationStore.createConversation({
    title: question,
    AI_providerName,
    AI_modelName,
    createdAt: currentTime,
    updatedAt: currentTime,
    msgList: [
      {
        type: "question",
        content: question,
        // 如果有图片路径，则将其添加到消息中
        ...(copiedImagePath && { imagePath: copiedImagePath }),
        createdAt: currentTime,
        updatedAt: currentTime,
      },
      {
        type: "answer",
        content: "",
        status: "loading",
        createdAt: currentTime,
        updatedAt: currentTime,
      },
    ],
  });

  // 更新当前选中的会话
  conversationStore.selectedId = conversationId;

  // 右侧界面--跳转到会话页面 -- 带参数 init 为新创建的会话的第一条消息id
  router.push(`/conversation/${conversationId}?type=new`);
};
</script>
